import { eventHandler, getQuery } from 'h3';
import { ApprovalStatus, RequestType } from '~/types/maintenance';
import { verifyAccessToken } from '~/utils/jwt-utils';
import { sleep, usePageResponseSuccess } from '~/utils/response';

/**
 * 生成模拟维保申请数据
 */
function generateMockRequests() {
  const requests = [];
  const drivers = ['张三', '李四', '王五', '赵六', '钱七'];
  const licensePlates = [
    '京A12345',
    '京B56789',
    '京C90123',
    '京D34567',
    '京E78901',
  ];

  for (let i = 1; i <= 50; i++) {
    const driverName = drivers[Math.floor(Math.random() * drivers.length)];
    const licensePlate =
      licensePlates[Math.floor(Math.random() * licensePlates.length)];
    const requestType =
      Math.random() > 0.5 ? RequestType.REPAIR : RequestType.MAINTENANCE;

    // 生成随机时间（最近30天内）
    const now = new Date();
    const randomHours = Math.floor(Math.random() * 30 * 24);
    const requestTime = new Date(now.getTime() - randomHours * 60 * 60 * 1000);

    // 生成随机描述
    const descriptions = [
      '车辆发动机异响，需要检查',
      '定期保养，更换机油和滤芯',
      '刹车系统故障，需要维修',
      '轮胎磨损严重，需要更换',
      '空调系统不制冷，需要检修',
      '电瓶电量不足，需要更换',
      '变速箱换挡不顺畅',
      '车辆底盘异响',
      '灯光系统故障',
      '雨刷器老化需要更换',
    ];

    // 生成随机图片URL（模拟多图）
    const imageCount = Math.floor(Math.random() * 3) + 1;
    const imageUrls = [];
    for (let j = 0; j < imageCount; j++) {
      imageUrls.push(`https://picsum.photos/400/300?random=${i}${j}`);
    }

    requests.push({
      requestId: i,
      vehicleId: Math.floor(Math.random() * 100) + 1,
      driverId: Math.floor(Math.random() * 50) + 1,
      licensePlate,
      driverName,
      requestType,
      description:
        descriptions[Math.floor(Math.random() * descriptions.length)],
      imageUrls: imageUrls.length > 0 ? imageUrls : undefined,
      requestTime: requestTime.toISOString(),
      approvalStatus: ApprovalStatus.PENDING,
    });
  }

  return requests;
}

const mockRequests = generateMockRequests();

export default eventHandler(async (event) => {
  const userinfo = verifyAccessToken(event);
  if (!userinfo) {
    return { code: 401, message: '未授权访问' };
  }

  await sleep(300);

  const { page, pageSize, licensePlate, driverName, requestType } =
    getQuery(event);

  // 规范化分页参数
  const pageRaw = Array.isArray(page) ? page[0] : page;
  const pageSizeRaw = Array.isArray(pageSize) ? pageSize[0] : pageSize;
  const pageNumber = Math.max(
    1,
    Number.parseInt(String(pageRaw ?? '1'), 10) || 1,
  );
  const pageSizeNumber = Math.min(
    100,
    Math.max(1, Number.parseInt(String(pageSizeRaw ?? '20'), 10) || 20),
  );

  // 筛选数据 - 只显示待审批的申请
  let filteredRequests = mockRequests.filter(
    (request) => request.approvalStatus === ApprovalStatus.PENDING,
  );

  // 过滤条件
  if (licensePlate) {
    const searchTerm = String(licensePlate).toLowerCase();
    filteredRequests = filteredRequests.filter((request) =>
      request.licensePlate.toLowerCase().includes(searchTerm),
    );
  }

  if (driverName) {
    const searchTerm = String(driverName).toLowerCase();
    filteredRequests = filteredRequests.filter((request) =>
      request.driverName?.toLowerCase().includes(searchTerm),
    );
  }

  if (requestType) {
    const typeFilter = String(requestType);
    filteredRequests = filteredRequests.filter(
      (request) => request.requestType === typeFilter,
    );
  }

  return usePageResponseSuccess(
    String(pageNumber),
    String(pageSizeNumber),
    filteredRequests,
    { message: '获取待审批列表成功' },
  );
});
